<template>
  <div class="chat-container">
    <div class="chat-header">
      <button class="back-button" @click="goBack">&#60;</button>
      <span>{{ friendUsername }}</span>
    </div>
    <div class="chat-window">
      <div class="messages" ref="messagesContainer">
        <div v-for="(message, index) in messages" :key="index" 
             :class="['message-item', message.senderId == userId ? 'right' : 'left']">
          <div class="message-bubble">
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="input-area">
      <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="输入消息..." />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { API_BASE_URL, WS_BASE_URL } from '@/config';
import axios from 'axios';
import { useWebSocketStore } from '@/stores/websocket';

interface Message {
  senderId: string;
  receiverId: string;
  content: string;
  timestamp: string;
}

const route = useRoute();
const router = useRouter();
const messages = ref<Message[]>([]);
const newMessage = ref('');
const userId = localStorage.getItem('userId');
const friendId = route.params.friendId as string;
const friendUsername = ref('');
const messagesContainer = ref<HTMLElement | null>(null);
const websocketStore = useWebSocketStore();

// 返回按钮
const goBack = () => {
  router.push('/friends');
};

// 获取好友信息
const getFriendInfo = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/users/${friendId}`);
    friendUsername.value = response.data.username;
  } catch (error: any) {
    console.error('获取好友信息失败:', error);
  }
};

// 获取聊天记录
const getChatHistory = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/chat/${userId}/${friendId}`);
    messages.value = response.data.map((message: any) => ({
      ...message,
      senderId: message.senderId,
      receiverId: message.receiverId
    }));
    scrollToBottom();
  } catch (error: any) {
    console.error('获取聊天记录失败:', error);
  }
};

// 发送消息
const sendMessage = () => {
  if (newMessage.value.trim() && websocketStore.ws) {
    const message: Message = {
      senderId: userId!,
      receiverId: friendId,
      content: newMessage.value,
      timestamp: new Date().toISOString()
    };
    websocketStore.ws.send(JSON.stringify(message));
    messages.value.push(message);
    newMessage.value = '';
    scrollToBottom();
  }
};

// 格式化时间
const formatTime = (timestamp: string) => {
  return new Date(timestamp).toLocaleTimeString();
};

// 滚动到最底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTo({
        top: messagesContainer.value.scrollHeight,
        behavior: 'smooth'
      });
    }
  });
};

onMounted(async () => {
  await getFriendInfo();
  await getChatHistory();

  // 监听 WebSocket 消息
  if (websocketStore.ws) {
    websocketStore.ws.onmessage = (event) => {
      const message: Message = JSON.parse(event.data);
      messages.value.push(message);
      scrollToBottom();
    };
  }
});
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 88vh;
  width: 100%;
  background-color: #f5f5f5;
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #409eff;
  color: white;
  font-size: 1.2em;
  font-weight: bold;
}

.back-button {
  background: none;
  border: none;
  color: white;
  font-size: 1.5em;
  cursor: pointer;
  margin-right: 10px;
}

.back-button:hover {
  opacity: 0.8;
}

.chat-window {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.messages {
  display: flex;
  flex-direction: column;
  gap: 10px;
  overflow-y: auto;
  height: 100%;
}

.message-item {
  display: flex;
}

.message-item.right {
  justify-content: flex-end;
}

.message-item.left {
  justify-content: flex-start;
}

.message-bubble {
  max-width: 60%;
  padding: 10px;
  border-radius: 10px;
  background-color: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.message-item.right .message-bubble {
  background-color: #409eff;
  color: white;
}

.message-item.left .message-bubble {
  background-color: #f5f7fa;
  color: black;
}

.message-text {
  word-wrap: break-word;
}

.message-time {
  font-size: 0.8em;
  color: #999;
  margin-top: 5px;
}

.input-area {
  display: flex;
  gap: 10px;
  padding: 10px;
  background-color: white;
  border-top: 1px solid #eee;
}

.input-area input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.input-area button {
  padding: 10px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.input-area button:hover {
  background-color: #66b1ff;
}
</style> 